define(['jquery', 'api', 'util', 'user', 'Vue', 'text!pages/index/producttrade.html', 'echarts', 'pages/index/goodsModel'], function($, api, util, user, Vue, tpl, echarts, goodsModel) {
    var vm,
        params = {},
        timer,
        timerQueryGoodHold,
        chartsDayData, //图标日线数据
        chartsTypes = C('producttrade_charts_types'),
        controller = {
            init: function(goodscode) {

                api.footerShow(0);
                api.setTitle(L('html_title_index_producttrade'));
                api.headerShow(1);
                api.headerTitle(L('html_title_index_producttrade'));
                api.headerRightTitle('定向交易');
                api.headerRightLink('#/order/transfer/' + goodscode);
                params.goodscode = goodscode;
                if (vm) {
                    vm.show = true;
                    vm.pop = 1;
                    vm.nav = 1;
                } else {
                    this.render();
                }

                this.refresh5({}); //先给个空5档
                this.loadGoodsInfo();

            },
            render: function() {
                var that = this;
                $('#pages').append('<div id="producttrader"></div>');
                vm = new Vue({
                    el: '#producttrader',
                    data: {
                        show: true,
                        loading: false,
                        userHold: {}, // 用户持仓汇总数据
                        userFund: {}, //用户资金 ，balance 可用资金,buyopencharge单笔手续费，,
                        goods: {},
                        hq: {}, // 行情
                        mindecimal: 0,
                        priceOptionType: '', //涨跌停价格单选按钮,up为涨停、down为跌停
                        hqdirect: '', //行情涨跌标识,up为涨停、down为跌停
                        upPrice: 0, //涨停价
                        downPrice: 0, //跌停价
                        formPrice: 0, //挂单价格
                        formNum: 1, //购买数量
                        formCount: 0, //购买总计
                        form: {
                            canamount: 0, //可买数:0,
                            type: 1, //1挂单,2应价
                            direct: 98 //买入，2卖出
                        },
                        slvolpricelevel: [],
                        sell_arr: [],
                        buy_arr: [],
                        pop: 1,
                        nav: 1,
                        desc: ''
                    },
                    watch: {
                        formPrice: function(now, old) { // 监控挂单价格输入
                            if (isNaN(now) || parseFloat(now) <= 0) {
                                this.formPrice = 1;
                            } else {
                                this.formPrice = this.formPrice;
                            }
                            if (now != vm.upPrice && now != vm.downPrice) {
                                vm.priceOptionType = '';
                            }
                            // 总计
                            this.formCountFunc(this.formPrice, this.formNum);
                        },
                        formNum: function(now, old) { // 监控挂单数量输入
                            if (!isNaN(now) || parseInt(now) > 0 || now == '') {
                                this.formNum = now ? parseInt(now) : '';
                            } else {
                                this.formNum = '';
                            }
                            this.formCountFunc(this.formPrice, this.formNum);
                        }

                    },
                    computed: {
                        // 涨停价
                        computedUpPrice: function() {
                            if (typeof this.hq == 'undefined') {
                                var settl = parseInt(this.goods.issueprice);
                            } else {
                                var settl = parseFloat(util.priceFormat(vm.mindecimal, this.hq.settl));
                            }
                            var
                                updownupperlimit = parseFloat(this.goods.updownupperlimit),
                                v = settl + updownupperlimit / 100 * settl;
                            var updowntype = this.goods.updowntype; //交易手续费类型:49比例，50固定,51不设涨停板

                            if (updowntype == 49) { //比例
                                v = v.toFixed(vm.mindecimal);
                            } else if (updowntype == 50) { //固定
                                v = (settl + updownupperlimit).toFixed(vm.mindecimal); //涨停
                            } else if (updowntype == 51) { //不设涨停板 3-51
                                //不显示价格区间
                                this.hasRange = true;
                            }

                            this.upPrice = v;
                            return v;
                        },
                        // 跌停价
                        computedDownPrice: function() {
                            // yessettl 昨日结算价格，updownlowerlimit 涨跌幅下线，updownlowerlimit 涨跌幅上线
                            if (typeof this.hq == 'undefined') {
                                var settl = parseInt(this.goods.issueprice);
                            } else {
                                var settl = parseFloat(util.priceFormat(vm.mindecimal, this.hq.settl));
                            }
                            var settl = parseFloat(util.priceFormat(vm.mindecimal, this.hq.settl)),
                                updownlowerlimit = this.goods.updownlowerlimit,
                                v = settl - updownlowerlimit / 100 * settl;



                            //是固定类型就用行情价

                            var updowntype = this.goods.updowntype; //交易手续费类型:49比例，50固定,51不设涨停板

                            if (updowntype == 49) { //比例 1-49
                                v = v.toFixed(vm.mindecimal);
                            } else if (updowntype == 50) { //固定 2-50
                                v = (settl - updownlowerlimit).toFixed(vm.mindecimal); //跌停
                            } else if (updowntype == 51) { //不设涨停板 3-51
                                //不显示价格区间
                                this.hasRange = true;
                            }



                            this.downPrice = v; //跌停价
                            return v;
                        },
                        // 买入卖出表单头
                        formTitle: function() {
                            var str = [];
                            if (this.form.type == 1) {
                                str.push('应价');
                            } else if (this.form.type == 2) {
                                str.push('挂单');
                            }
                            if (this.form.direct == 98) {
                                str.push('买入');
                            } else if (this.form.direct == 115) {
                                str.push('卖出');
                            }
                            return str.join('');
                        },
                        formTitlePrice: function() {
                            var str = [];
                            if (this.form.type == 1) {
                                if (this.form.direct == 98) {
                                    str.push('买入价格');
                                } else if (this.form.direct == 115) {
                                    str.push('卖出价格');
                                }
                            } else if (this.form.type == 2) {
                                str.push('挂单价格');
                            }
                            return str.join('');
                        },
                        formTitleNum: function() {
                            var str = [];
                            if (this.form.type == 1) {
                                str.push('应价数量');
                            } else if (this.form.type == 2) {
                                str.push('挂单数量');
                            }
                            return str.join('');
                        },
                        formTitleNumMax: function() {
                            var str = [];
                            if (this.form.type == 1) {
                                if (this.form.direct == 98) {
                                    str.push('可买数量');
                                } else if (this.form.direct == 115) {
                                    str.push('可卖数量');
                                }
                            } else if (this.form.type == 2) {
                                str.push('可挂数量');
                            }
                            return str.join('');
                        },
                        formTitlePriceTotal: function() {
                            var str = [];
                            if (this.form.type == 1) {
                                str.push('应价金额');
                            } else if (this.form.type == 2) {
                                str.push('挂单金额');
                            }
                            return str.join('');
                        },
                    },
                    filters: {
                        chartsTypeName: function(v) {
                            if (v) {
                                if (v == 'k') {
                                    return '日线';
                                } else if (v == 'line') {
                                    return '历史价格';
                                }
                            } else {
                                return '';
                            }
                        },
                        priceFormat: function(v) {
                            var mindecimal = 2;
                            if (typeof vm != 'undefined') {
                                mindecimal = vm.mindecimal;
                            }
                            return util.priceFormat(mindecimal, v);
                        },
                        range: function(v) { //涨跌价
                            var prefix = '';
                            if (v > 0)
                                prefix = '+';
                            return isNaN(v) ? '0' : prefix + (util.priceFormat(vm.goods.mindecimal, v));
                        },
                        rate: function(v) { //涨跌比
                            var prefix = '';
                            if (v > 0)
                                prefix = '+';
                            return isNaN(v) ? '0' : prefix + (v.toFixed(2)) + '%';
                        },
                        toFixed: function(s) {
                            return !isNaN(s) ? s.toFixed(2) : '0.00';
                        },
                        price: function(s, mindecimal) {
                            return s ? util.priceFormat(mindecimal, s) : '0.00';
                        },
                        fivePrice: function(v) {
                            return !isNaN(v) ? util.priceFormat(vm.goods.mindecimal, v) : '-';
                        },
                        time: function(s) {
                            return +s ? new Date((+s) * 1000).format('h:m:s') : '-';
                        }
                    },
                    methods: {
                        resetForm: function() {
                            this.form = {
                                maxnum: 0,
                                type: 1, //1挂单,2应价
                                direct: 98, //买入，2卖出
                                desc: ''
                            };
                            this.priceOptionType = ''; //涨跌停价格单选按钮,up为涨停、down为跌停
                            this.upPrice = 0; //涨停价
                            this.downPrice = 0; //跌停价
                            this.formPrice = 0; //挂单价格
                            this.formNum = 1; //购买数量
                            this.formCount = 0; //购买总计

                            this.hideForm();
                        },
                        formCountFunc: function(price, num) {
                            if (this.form.type == 1) {
                                vm.formCount = util.priceFormat(vm.mindecimal, price * num);
                            } else {
                                vm.formCount = util.priceFormat(0, price * num);
                            }
                        },
                        //挂单、应价买入卖出表单弹出
                        showForm: function(type, direct, price, canamount) {
                            if (!user.checkLogin())
                                return;
                            // 初始化可交易数量
                            this.form.canamount = 0;

                            var holdamount = this.userHold[this.goods.goodscode] ? parseInt(this.userHold[this.goods.goodscode].holdamount) : 0,
                                allowsellamount = this.userHold[this.goods.goodscode] ? this.userHold[this.goods.goodscode].allowsellamount : 0; //当前商品持仓的可用数量
                            this.form.type = type; // 应价1，挂单2
                            this.form.direct = direct; //买98，115卖
                            this.formPrice = 0;
                            this.pop = 2;

                            if (price) { //应价
                                this.form.canamount = Math.min(parseInt(canamount), parseInt(holdamount)); //应价买入卖出数量
                                this.formPrice = price; //应价价格
                                //可应数量
                                if (direct == 98) {
                                    that.ltbuyCount(this.goods.goodscode);
                                } else if (direct == 115) {
                                    that.ltsellCount(this.goods.goodscode);
                                }

                            } else { //挂单
                                //挂单价格默认值是行情价
                                this.formPrice = util.priceFormat(this.mindecimal, this.hq.price);

                                if (direct == 98) {
                                    that.ltGoodsNewest(this.goods.goodscode, 'b');
                                    // 可挂买数量
                                    //	              				this.form.canamount = util.getCanamount({
                                    //	    	        				direct: direct,
                                    //	    	        				goods: vm.goods,
                                    //	    	        				hqprice: vm.hq.price,
                                    //	    	        				holdamount: holdamount,
                                    //	    	        				balance: vm.userFund.balance,
                                    //	    	        				inprice: this.formPrice
                                    //	    	        			});
                                    //	    	        			this.form.canamount = parseInt(this.form.canamount);
                                } else if (direct == 115) {
                                    that.ltGoodsNewest(this.goods.goodscode, 's');
                                    // 可挂卖数量，=当前商品持仓的可用数量 order.allowsellamount
                                    //            					this.form.canamount = parseInt(allowsellamount);
                                }
                            }

                        },
                        priceOption: function(opt) { //挂单涨跌停价格选择
                            vm.priceOptionType = opt;
                            if (opt == 'up') {
                                vm.formPrice = vm.upPrice;
                            } else if (opt == 'down') {
                                vm.formPrice = vm.downPrice;
                            }
                        },
                        switchNav: function(i) {
                            this.nav = i
                            if (i == 2) {
                                setTimeout(function() {
                                    that.renderChart();
                                }, 0)
                            }
                            if (i == 3) {
                                setTimeout(function() {
                                    that.loadDesc(vm.goods.goodscode);
                                }, 0)
                            }
                        },
                        hideForm: function() {
                            this.pop = 1;
                        },
                        subForm: function(type, direct) { //挂单、应价买入卖出表单提交
                            this.formNum = parseInt(this.formNum);
                            if (this.form.canamount < this.formNum) { //提交数量不能大于可买数量
                                //  	           			var str = ['填写数量不能大于'];
                                //  	           			if(direct==98){
                                //  	           				str.push('可买数量');
                                //  	           			}else{
                                //  	           				str.push('可卖数量');
                                //  	           			}
                                //  	           			util.msg(str.join(''));
                                //	    	           		return;
                            }

                            if (type == 1) { //应价
                                if (direct === 98) {
                                    that.buy();
                                } else if (direct === 115) {
                                    that.sell();
                                }
                            } else if (type === 2) { //挂单
                                if (direct === 98) {
                                    that.ltbuy();
                                } else if (direct === 115) {
                                    that.ltsell();
                                }
                            }

                        },
                        chartsChange: function(type) { ////
                            if (type == 'k' || type == 'line') {
                                option = that.createOption(chartsDayData, type);
                                charts = echarts.init($('#charts').get(0));
                                charts.setOption(option, true);
                            }
                        }
                    },
                    template: tpl
                });
            },
            ltGoodsNewest: function(code, direct) { //挂单买入卖出可挂数量
                //direct=b b 挂单买入 s 挂单卖出
                api.ltGoodsNewest({ goodscode: code, direct: direct }, function(rs) {
                    if (rs.retcode === '0' && rs.data) {
                        vm.form.canamount = parseInt(rs.data.canpurchaseamount);
                    }
                });
            },
            ltsellCount: function(code) { //应价卖出数量
                api.ltsellCount({ goodscode: code }, function(rs) {
                    if (rs.retcode === '0' && rs.data) {
                        vm.form.canamount = parseInt(rs.data.canpurchaseamount);
                    }
                });
            },
            ltbuyCount: function(code) { //应价买入数量
                api.ltbuyCount({ goodscode: code }, function(rs) {
                    if (rs.retcode === '0' && rs.data) {
                        vm.form.canamount = parseInt(rs.data.canpurchaseamount);
                    }
                });
            },
            loadDesc: function(goodscode) { //商品介绍
                vm.loading = true;
                api.goodsDesc(
                    goodscode,
                    function(rs) { //suc
                        vm.loading = false;
                        if (rs.retcode == 0) {
                            vm.desc = rs.data.goodsdesc; //商品介绍
                        }
                    },
                    function() { //err
                        vm.loading = false;
                    }
                );
            },
            ltbuy: function() { //挂单买入
                var that = this;

                if (this.isValid(vm.form)) {
                    api.createLtOrder({ goodscode: params.goodscode, orderamount: vm.formNum, orderprice: util.unPriceFormat(vm.goods.mindecimal, vm.formPrice) },
                        function(rs) {
                            if (rs.retcode == '0') {
                                util.msg('买入挂单成功');
                                vm.resetForm();
                                setTimeout(that.queryGoodHold(), 500);
                            } else if (rs.retcode !== '0') {
                                util.dealErrorCode(rs.retcode);
                            }
                        }
                    );
                }
            },
            ltsell: function() { //挂单卖出
                var that = this;
                if (this.isValid(vm.form)) {
                    api.sellLtOrder({ goodscode: params.goodscode, orderamount: vm.formNum, orderprice: util.unPriceFormat(vm.goods.mindecimal, vm.formPrice) },
                        function(rs) {
                            if (rs.retcode == '0') {
                                util.msg('卖出挂单成功');
                                vm.resetForm();
                                setTimeout(that.queryGoodHold(), 500);
                            } else if (rs.retcode !== '0') {
                                util.dealErrorCode(rs.retcode);
                            }
                        }
                    );
                }
            },
            buy: function() { //应价买入
                var that = this;
                if (this.isValid(vm.form)) {
                    api.createLtOrderCater({ goodscode: params.goodscode, orderamount: vm.formNum, orderprice: vm.formPrice },
                        function(rs) {
                            if (rs.retcode == '0') {
                                util.msg('买入成功');
                                vm.resetForm();
                                setTimeout(that.queryGoodHold(), 500);
                            } else if (rs.retcode !== '0') {
                                util.dealErrorCode(rs.retcode);
                            }
                        }
                    );
                }
            },
            sell: function() { //应价卖出
                var that = this;
                if (this.isValid(vm.form)) {
                    api.sellOrderCater({ goodscode: params.goodscode, orderamount: vm.formNum, orderprice: vm.formPrice },
                        function(rs) {
                            if (rs.retcode == '0') {
                                util.msg('卖出成功');
                                vm.resetForm();
                                setTimeout(that.queryGoodHold(), 500);
                            } else if (rs.retcode !== '0') {
                                util.dealErrorCode(rs.retcode);
                            }
                        }
                    );
                }
            },
            isValid: function(data) { //表单验证
                //      	return true;//待补充
                var error = false,
                    errorHash = {
                        //		           	price:'请填写价格！',
                        //					count:'请填写数量！'
                    };
                for (var key in errorHash) {
                    if (data[key] == '') {
                        error = errorHash[key];
                        break;
                    }
                }

                if ((isNaN(vm.formPrice) || vm.formPrice == '' || vm.formPrice <= 0)) {
                    error = '价格必须大于0';
                }
                if (isNaN(vm.formNum) || vm.formNum == '' || vm.formNum <= 0) {
                    error = '数量必须大于0';
                }
                if (isNaN(vm.form.canamount) || vm.form.canamount <= 0 || vm.formNum > vm.form.canamount) {
                    error = '数量不足';
                }

                if (error) {
                    util.msg(error);
                    return false;
                } else {
                    return true;
                }
            },
            loadGoodsInfo: function() {
                var that = this,
                    goodscode = params.goodscode,
                    cb = function() {
                        if (user.isLogin()) {
                            that.queryGoodHold();
                            that.initUserInfo();
                        }

                        that.timer(); //行情开始
                    };
                vm.loading = true;

                api.goodsInfo({
                    data: { goodscode: params.goodscode },
                    success: function(rs) {
                        vm.loading = false;

                        if (rs.retcode == '0') {
                            goodsModel.addGoods(rs.data);
                            vm.goods = goodsModel.codeToGoods[params.goodscode];
                            vm.mindecimal = vm.goods.mindecimal;
                            cb();
                        } else {
                            util.msg('商品数据加载失败！')
                        }
                    }
                });
            },
            initUserInfo: function() {
                api.userInfo(function(rs) {
                    if (rs.retcode == '0') {
                        vm.userFund = rs.data;
                    } else {
                        util.msg('用户信息获取失败！');
                    }
                });
            },
            queryGoodHold: function() {
                var that = this,
                    cb = function() {
                        if (user.isLogin()) {
                            that.queryGoodHold();
                        }
                    };
                api.queryGoodHold({}, function(rs) { // 持仓汇总
                    if (rs.retcode === '0' && rs.data) {
                        rs.data.map(function(item) {
                            if (item.goodscode == params.goodscode) {
                                vm.userHold[item.goodscode] = item;
                            } else {
                                vm.userHold[item.goodscode] = {};
                            }
                        });
                    } else {
                        if (timerQueryGoodHold)
                            clearTimeout(timerQueryGoodHold);
                        timerQueryGoodHold = setTimeout(cb, 1000);
                    }
                });
            },
            timer: function() {
                var that = this,
                    cb = function() {
                        that.timer();
                    };
                api.quotation({
                    data: { goodscode: params.goodscode },
                    success: function(rs) {
                        if (rs.retcode === '0' && rs.data) {
                            if (typeof rs.data[0].slvolpricelevel != 'undefined') {
                                that.refresh5(rs.data[0].slvolpricelevel); //5档
                            } else {
                                that.refresh5({}); //空5档
                            }
                            that.refreshHq.call(that, rs.data[0]);
                            if (vm.show) {
                                if (timer)
                                    clearTimeout(timer);
                                timer = setTimeout(cb, util.cfg.refreshTime);
                            }
                        } else {
                            if (vm.show) {
                                if (timer)
                                    clearTimeout(timer);
                                timer = setTimeout(cb, util.cfg.refreshTime);
                            }
                        }

                    },
                    error: function(xhr, status) {
                        var error = status == 'timeout' ? '网络超时，' : '';
                        error += '加载行情数据失败！';
                        util.msg(error);
                        if (timer)
                            clearTimeout(timer);
                        timer = setTimeout(cb, util.cfg.refreshTime);
                    }
                })
            },
            refresh5: function(data) { //刷新5档，默认升序
                /*"slvolpricelevel":
                 {
                 "buy":
                 [
                 {
                 "buyprice": "32100",
                 "buyqty": "1"
                 },
                 {
                 "buyprice": "31700",
                 "buyqty": "1"
                 }
                 ],
                 "sell":
                 [
                 {
                 "sellprice": "32000",
                 "sellqty": "1"
                 },
                 {
                 "sellprice": "32100",
                 "sellqty": "20"
                 },
                 {
                 "sellprice": "32200",
                 "sellqty": "1"
                 }
                 ]
                 }*/
                var selltemp = [
                        [5, '-', '-'],
                        [4, '-', '-'],
                        [3, '-', '-'],
                        [2, '-', '-'],
                        [1, '-', '-']
                    ],
                    buytemp = [
                        [1, '-', '-'],
                        [2, '-', '-'],
                        [3, '-', '-'],
                        [4, '-', '-'],
                        [5, '-', '-']
                    ],
                    sell_arr = [],
                    sellLen = typeof data.sell != 'undefined' ? data.sell.length : 0,
                    buy_arr = [],
                    buyLen = typeof data.buy != 'undefined' ? data.buy.length : 0;

                if (sellLen) {
                    var sell_j = 4;
                    for (var i = 0; i < sellLen; i++) {
                        selltemp[sell_j][1] = data.sell[i].sellprice; //价格
                        selltemp[sell_j][2] = data.sell[i].sellqty; //数量
                        sell_j--;
                    }
                }
                vm.sell_arr = selltemp;

                if (buyLen) {
                    for (var i = 0; i < buyLen; i++) {
                        buytemp[i][1] = data.buy[i].buyprice; //价格
                        buytemp[i][2] = data.buy[i].buyqty; //数量
                    }
                }
                vm.buy_arr = buytemp;
            },
            refreshHq: function(o) {
                var temp = {
                    time: o.time,
                    open: o.open,
                    close: o.yesclose,
                    high: o.high,
                    low: o.low,
                    settl: o.yessettl,
                    price: +o.price ? o.price : o.yesclose, // 现价（没有就取昨收价）
                    pricerange: +o.price ? (o.price - o.yesclose) : 0, //涨跌幅价格
                    pricerate: +o.price ? (o.price - o.yesclose) * 100 / o.yesclose : 0, //涨幅比例=当前-昨日收盘价
                    qty: o.qty
                };

                if (temp.price > temp.close) {
                    vm.hqdirect = 'up';
                } else if (temp.price < temp.close) {
                    vm.hqdirect = 'down';
                }
                vm.hq = temp;
            },
            renderChart: function() {
                var option,
                    that = this;

                if (typeof chartsTypes != 'object' || !chartsTypes.length) {
                    util.msg('缺少图标配置');
                    return;
                }
                api.kDay({
                    data: { goodscode: params.goodscode },
                    success: function(rs) {
                        if (rs.retcode == '0' && rs.data) {
                            chartsDayData = rs.data;
                            option = that.createOption(rs.data, chartsTypes[0]);
                            charts = echarts.init($('#charts').get(0));
                            charts.setOption(option, true);
                        }
                    },
                    error: function() {}
                });
            },
            createOption: function(data, type) {
                //              	if($.inArray('k',chartsTypes)>=0){
                //              		type = chartsTypes[0];
                //              	}
                //                  if (type == undefined){
                //                  	type = 'k';
                //                  }
                var categoryData = [],
                    values = [],
                    volumns = [];
                var calculateMA = function(field, data) {
                    var result = [];
                    for (var i = 0, len = data.length; i < len; i++) {

                        if (field == 'close') {
                            result.push(util.priceFormat(vm.mindecimal, data[i].close));
                        } else if (field == 'high') {
                            result.push(util.priceFormat(vm.mindecimal, data[i].high));
                        } else if (field == 'low') {
                            result.push(util.priceFormat(vm.mindecimal, data[i].low));
                        }
                    }
                    return result;
                };


                for (var i = 0, row; i < data.length; i++) {
                    row = data[i];
                    categoryData.push(new Date(row.time * 1000).format('yyyy-MM-dd'));

                    // 开高低收量
                    values.push([
                        parseFloat(util.priceFormat(vm.mindecimal, row.open)),
                        parseFloat(util.priceFormat(vm.mindecimal, row.close)),
                        parseFloat(util.priceFormat(vm.mindecimal, row.low)),
                        parseFloat(util.priceFormat(vm.mindecimal, row.high)),
                        parseInt(row.trunoverqty) //成交量
                    ]);
                    volumns.push(parseInt(row.trunoverqty))
                }


                if (type == 'k') {
                    return {
                        backgroundColor: '#eee',
                        animation: false,
                        legend: { // 底部图标
                            bottom: 10,
                            left: 'center',
                            data: ['日K线']
                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'line'
                            }
                            //                              ,
                            //                              formatter: function(params, ticket, callback) {
                            //                                  var f = params[0].name;
                            //                                  f += '<br/>  开盘 : ' + params[0].data[0] + '<br/>  最高 : ' + params[0].data[3];
                            //                                  f += '<br/>  最低 : ' + params[0].data[2] + '<br/>  收盘 : ' + params[0].data[1];
                            //                                  return f
                            //                              }
                        },
                        toolbox: { // 工具栏隐藏
                            show: false
                        },
                        brush: { //筛选刷 http://echarts.baidu.com/option.html#brush
                            xAxisIndex: 'all',
                            brushLink: 'all',
                            outOfBrush: {
                                colorAlpha: 0.1
                            }
                        },
                        grid: [{ // 折线图
                                top: '10%',
                                left: '13%',
                                right: '5%',
                                height: '50%'
                            },
                            { // 柱状图
                                left: '10%',
                                right: '8%',
                                top: '65%',
                                height: '16%'
                            }
                        ],
                        xAxis: [ //http://echarts.baidu.com/option.html#xAxis
                            {
                                type: 'category',
                                data: categoryData,
                                scale: true,
                                boundaryGap: true, //坐标轴两边留白策略，类目轴和非类目轴的设置和表现不一样。
                                axisLine: { onZero: false },
                                splitLine: { show: false },
                                splitNumber: 10
                            },
                            {
                                type: 'category',
                                gridIndex: 1,
                                data: categoryData,
                                scale: true,
                                boundaryGap: true,
                                axisLine: { onZero: false },
                                axisTick: { show: false },
                                splitLine: { show: false },
                                axisLabel: { show: false },
                                splitNumber: 10
                            }
                        ],
                        yAxis: [{
                                scale: true,
                                boundaryGap: ['20%', '20%'], //坐标图上下留白
                                splitArea: {
                                    show: true
                                }
                            },
                            {
                                scale: true,
                                gridIndex: 1,
                                splitNumber: 2,
                                axisLabel: { show: false },
                                axisLine: { show: false },
                                axisTick: { show: false },
                                splitLine: { show: false }

                            }
                        ],
                        dataZoom: [{
                                type: 'inside',
                                xAxisIndex: [0, 1],
                                start: 0,
                                end: 100
                            },
                            {
                                show: true,
                                xAxisIndex: [0, 1],
                                type: 'slider',
                                top: '85%',
                                start: 0,
                                end: 100
                            }
                        ],
                        series: [{ // 日K线
                                name: '日K线',
                                type: 'candlestick',
                                data: values,
                                itemStyle: {
                                    normal: {
                                        borderColor: null,
                                        borderColor0: null,
                                        color0: '#080' //阴线填充色
                                    }
                                },
                                tooltip: {
                                    formatter: function(params, ticket, callback) {
                                        var f = params[0].name;
                                        f += '<br/>  开盘 : ' + params[0].data[0] + '<br/>  最高 : ' + params[0].data[3];
                                        f += '<br/>  最低 : ' + params[0].data[2] + '<br/>  收盘 : ' + params[0].data[1];
                                        return f
                                    }
                                }
                            },
                            {
                                name: '成交量',
                                type: 'bar',
                                xAxisIndex: 1,
                                yAxisIndex: 1,
                                data: volumns
                            }
                        ]
                    }; //end return

                } else if (type == 'line') {
                    return {
                        backgroundColor: '#eee',
                        animation: false,
                        legend: { // 底部图标
                            bottom: 10,
                            left: 'center',
                            data: ['最高价', '昨收价', '最低价']
                        },
                        tooltip: { // 竖线提示
                            trigger: 'axis',
                            axisPointer: {
                                type: 'line'
                            }
                        },
                        toolbox: { // 工具栏隐藏
                            show: false
                        },
                        brush: { //筛选刷 http://echarts.baidu.com/option.html#brush
                            xAxisIndex: 'all',
                            brushLink: 'all',
                            outOfBrush: {
                                colorAlpha: 0.1
                            }
                        },
                        grid: [{ // 折线图
                                top: '10%',
                                left: '13%',
                                right: '5%',
                                height: '50%'
                            },
                            { // 柱状图
                                left: '10%',
                                right: '8%',
                                top: '65%',
                                height: '16%'
                            }
                        ],
                        xAxis: [ //http://echarts.baidu.com/option.html#xAxis
                            {
                                type: 'category',
                                data: categoryData,
                                scale: true,
                                boundaryGap: true, //坐标轴两边留白策略，类目轴和非类目轴的设置和表现不一样。
                                axisLine: { onZero: false },
                                splitLine: { show: false },
                                splitNumber: 10
                            },
                            {
                                type: 'category',
                                gridIndex: 1,
                                data: categoryData,
                                scale: true,
                                boundaryGap: true,
                                axisLine: { onZero: false },
                                axisTick: { show: false },
                                splitLine: { show: false },
                                axisLabel: { show: false },
                                splitNumber: 10
                            }
                        ],
                        yAxis: [{
                                scale: true,
                                boundaryGap: ['20%', '20%'], //坐标图上下留白
                                splitArea: {
                                    show: true
                                }
                            },
                            {
                                scale: true,
                                gridIndex: 1,
                                splitNumber: 2,
                                axisLabel: { show: false },
                                axisLine: { show: false },
                                axisTick: { show: false },
                                splitLine: { show: false }
                            }
                        ],
                        dataZoom: [{
                                type: 'inside',
                                xAxisIndex: [0, 1],
                                start: 0,
                                end: 100
                            },
                            {
                                show: true,
                                xAxisIndex: [0, 1],
                                type: 'slider',
                                top: '85%',
                                start: 0,
                                end: 100
                            }
                        ],
                        series: [{
                                name: '最高价',
                                type: 'line',
                                data: calculateMA('high', data),
                                smooth: true,
                                lineStyle: {
                                    normal: { opacity: 0.5 }
                                }
                            },
                            {
                                name: '昨收价',
                                type: 'line',
                                data: calculateMA('close', data),
                                smooth: true,
                                lineStyle: {
                                    normal: { opacity: 0.5 }
                                }
                            },
                            {
                                name: '最低价',
                                type: 'line',
                                data: calculateMA('low', data),
                                smooth: true,
                                lineStyle: {
                                    normal: { opacity: 0.5 }
                                }
                            },
                            {
                                name: '成交量',
                                type: 'bar',
                                xAxisIndex: 1,
                                yAxisIndex: 1,
                                data: volumns
                            }
                        ]
                    }; // end return 
                }
            },
            //	   createLineOption:function(data){
            //	    	var categoryData = [],
            //	    		values = [],
            //	    		volumns= [];
            //  		var calculateMA = function(field, data) {
            //			    var result = [];
            //			    for (var i = 0, len = data.length; i < len; i++) {
            //			
            //					if(field=='close'){
            //						result.push(util.priceFormat(vm.mindecimal,data[i].close));
            //					}
            //					else if(field=='high'){
            //						result.push(util.priceFormat(vm.mindecimal,data[i].high));
            //					}
            //					else if(field=='low'){
            //						result.push(util.priceFormat(vm.mindecimal,data[i].low));
            //					}
            //			    }
            //			    return result;
            //			};
            //
            //	    		
            //	    	for(var i=0,row;i<data.length;i++){
            //	    	   row = data[i];
            //	    	   categoryData.push(new Date(row.time*1000).format('yyyy-MM-dd'));
            //
            //				// 开高低收量
            //	    	   values.push([
            //	    	   	util.priceFormat(vm.mindecimal,row.open),
            //	    	   	util.priceFormat(vm.mindecimal,row.close),
            //	    	   	util.priceFormat(vm.mindecimal,row.low),
            //	    	   	util.priceFormat(vm.mindecimal,row.high),
            //	    	   	parseInt(row.trunoverqty) //成交量
            //	    	   ]);
            //	    	   volumns.push(parseInt(row.trunoverqty))
            //	    	}
            //
            //	    	
            //	    },
            onRouteChange: function() {
                if (vm) {
                    vm.resetForm();
                    vm.show = false;
                }
                if (timer)
                    clearTimeout(timer);
            }
        }
    return controller;
});